package Scheme101;

import java.util.*;

public class Environment {

    private Map<String, Cell> dict;
    private Environment external;

    public Environment(Environment ext) {
        dict = new HashMap<String, Cell>();
        external = ext;
    }

    public void add(String name, Cell cell) {
        dict.put(name, cell);
    }

    public void set(String name, Cell cell) {
        if (!dict.containsKey(name)) {
            if(external == null){
                System.out.println("set!: " + name + " has not been declared");
                System.exit(1);
            }
            external.set(name, cell);
            return;
        }
        dict.put(name, cell);
    }

    public void clear(){
        dict.clear();
    }

    public Cell get(String name) {
        if (dict.containsKey(name)) {
            return dict.get(name);
        } else if (external == null) {
            System.out.println("variable " + name + " has not been declared");
            System.exit(1);
        }
        return external.get(name);
    }

    public String toString(){
        return dict.toString();
    }
}
